import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
// import { ElMessage } from "element-plus";
import { staticRoutes, anyRoutes } from "@/router/routes";
import type { RouteRecordRaw } from "vue-router";
import {
  loginApi,
  logoutApi,
  getUserInfoApi,
  getUserInfoMockApi,
} from "@/api/acl/login";
import router from "@/router";

const modules = import.meta.glob(["@/views/**/*.vue", "@/layout/**/*.vue"]);
// console.log(modules);

const addComponent = (routes: RouteRecordRaw[]) => {
  routes.forEach((route) => {
    route.component = modules["/src" + route.component];
    if (route.children && route.children.length) {
      addComponent(route.children);
    }
  });
};

const addRoutes = (routes: RouteRecordRaw[]) => {
  routes.forEach((route) => {
    router.addRoute(route);
  });
};

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string,
    name: "",
    avatar: "",
    menuRoutes: [],
    buttons: [],
    routes: [],
  }),

  actions: {
    // 登录
    async login(username: string, password: string) {
      const { token } = await loginApi(username, password);
      this.token = token; // 存储在pinia中
      setToken(token); // 存储在localStorage中
    },
    // 登出
    async logout() {
      await logoutApi(); // 发送请求，退出登录
      this.reset(); // 清空本地数据
    },

    async getInfo() {
      const res = await getUserInfoMockApi();
      this.name = res.name;
      this.avatar = res.avatar;
      this.buttons = res.buttons; // 按钮权限列表
      this.routes = res.routes; // 路由权限列表

      // 将请求返回值路由表中组件由字符串 -> 变成真正组件
      addComponent(res.routes as any);
      addRoutes([...res.routes, ...anyRoutes] as any);

      this.menuRoutes = [...staticRoutes, ...res.routes] as any; // 左侧菜单
    },

    reset() {
      // 删除localStorage中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.$reset();
    },
  },
});
